import asyncio
import datetime
import traceback

import aioredis
import pymongo
import time
import random
import string
import sys
from cmcc_10086 import reg

from cmcc_10086 import re_send

client = pymongo.MongoClient('mongodb://cs_user:cmcc5188@localhost:12018/cs_recharge')
db = client.cs_recharge
coll = db.cmcc_username
loop = asyncio.get_event_loop()
redis = loop.run_until_complete(
    aioredis.create_redis(address=('localhost', 6379), db=0, loop=loop)
)


def gen_nonce_str(N=4):
    return ''.join(random.choice(string.ascii_lowercase) for _ in range(N)) + ''.join(
        random.choice(string.digits) for _ in range(N))


async def auto_reg(email, passwd, conn):
    for _ in range(6):
        res = await reg(email, passwd, conn)
        print(res, email)
        if res['code'] == 0:
            print(email, '|', res.get("message"))
            # coll.insert_one({"username": _data[0], "emailpasswd": _data[1], 'passwd': passwd, 'is_reg': '1',
            #                  'send_time': time.time()})
            coll.update_one({"username": email}, {"$set": {"is_reg": "1", "send_time": time.time()}})
            return
        if '存在' in res.get("message", ""):
            return


def main():
    # dateline = datetime.datetime(2019, 2, 27)
    c = coll.find({"is_reg": "33"}).limit(1)
    tasks = []
    for obj in c:
        try:
            #if '163.com' not in obj['username']:
            #    continue
            print(obj)
            task = asyncio.ensure_future(auto_reg(obj['username'], obj['passwd'], redis))
            tasks.append(task)
            if len(tasks) > 0:
                try:
                    results = loop.run_until_complete(asyncio.wait(tasks, timeout=10))
                except Exception as e:
                    traceback.print_exc()
                tasks = []
                print(results)

        except Exception as e:
            print(e)

def main2():
    now = datetime.datetime(2019, 2, 27, 9)
    coll.update_many({"is_reg": "8"}, {"$set": {"is_reg": "1"}})
    objs = coll.find({"is_reg": "2"})
    # objs = coll.find({"username": sys.argv[2]})
    tasks = []
    for obj in objs:
        print(obj)
        coll.update_one(obj, {"$set": {"is_reg": "1", "send_time": time.time()}})
        task = asyncio.ensure_future(re_send(obj['username'], redis))
        tasks.append(task)
    if tasks:
        try:
            print(loop.run_until_complete(asyncio.wait(tasks)))
        except Exception as e:
            traceback.print_exc()


def main3():
    with open("username.txt", encoding='gbk') as f:
        for line in f:
            line = line.strip()
            data = line.split("----")
            passwd = gen_nonce_str(4)
            obj = coll.find_one({"username": data[1]})
            if obj:
                continue
            else:
                print(data[1], data[2])
                coll.insert_one({"username": data[1], "emailpasswd": data[2], "passwd": passwd, "is_reg": "33"})

def main4():
    objs = coll.find({"username": sys.argv[2]})
    tasks = []
    for obj in objs:
        print(obj)
        task = asyncio.ensure_future(re_send(obj['username'], redis))
        tasks.append(task)
    if tasks:
        try:
            print(loop.run_until_complete(asyncio.wait(tasks)))
        except Exception as e:
            traceback.print_exc()

if __name__ == '__main__':
    if sys.argv[1] == 'reg':
        main()
        print("任务结束")
    elif sys.argv[1] == 're_send':
        while True:
            main2()
            print("休息一下")
            time.sleep(3*60)
    elif sys.argv[1] == 'add':
        main3()
    elif sys.argv[1] == 're2':
        main4()
